如何在Python中把一个列表作为一行追加到Pandas DataFrame中 您所在的位置:网站首页 python dataframe 新增一行 如何在Python中把一个列表作为一行追加到Pandas DataFrame中

如何在Python中把一个列表作为一行追加到Pandas DataFrame中

2023-09-07 01:02| 来源: 网络整理| 查看: 265

如何在Python中把一个列表作为一行追加到Pandas DataFrame中

在这篇文章中,我们将看到如何在Python中把一个列表作为行追加到pandas数据框中。它可以通过三种方式完成。

使用loc[] 使用iloc[] 使用append() 使用loc[]方法追加列表

Pandas DataFrame.loc属性通过标签或布尔数组访问指定DataFrame中的一组行和列。

让我们把清单上的内容分步附上:

第1步:使用列表创建一个简单的数据框架。

import pandas as pd   # List Person = [ ['Satyam', 21, 'Patna' , 'India' ],             ['Anurag', 23, 'Delhi' , 'India' ],             ['Shubham', 27, 'Coimbatore' , 'India' ]]   #Create a DataFrame object df = pd.DataFrame(Person,                   columns = ['Name' , 'Age', 'City' , 'Country'])   # display display(df)

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?

第2步:使用loc将新的列表追加到一个数据框中。

# New list for append into df list = ["Saurabh", 23, "Delhi", "india"]   # using loc methods df.loc[len(df)] = list   # display display(df)

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?

使用iloc[]方法追加列表

Pandas DataFrame.iloc方法访问基于整数位置的索引,用于按位置选择。

示例:

# import module import pandas as pd   # List Person = [ ['Satyam', 21, 'Patna' , 'India' ],             ['Anurag', 23, 'Delhi' , 'India' ],             ['Shubham', 27, 'Coimbatore' , 'India' ],             ["Saurabh", 23, "Delhi", "india"]]   #Create a DataFrame object df = pd.DataFrame(Person,                   columns = ['Name' , 'Age', 'City' , 'Country'])   # new list to append into df list = ['Ujjawal', 22, 'Fathua', 'India']   # using iloc df.iloc[2] = list   # display display(df)

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?

注意 – 它用于基于位置的索引,所以它只对现有的索引起作用,并取代了行元素。

使用append()方法追加列表

Pandas dataframe.append()函数用于将其他数据框架的行追加到给定数据框架的末尾,返回一个新的数据框架对象。

示例:

# import module import pandas as pd   # List Person = [ ['Satyam', 21, 'Patna' , 'India' ],             ['Anurag', 23, 'Delhi' , 'India' ],             ['Shubham', 27, 'Coimbatore' , 'India' ]]   #Create a DataFrame object df = pd.DataFrame(Person,                   columns = ['Name' , 'Age', 'City' , 'Country'])   # new list to append into df list = [["Manjeet", 25, "Delhi", "india"]]   # using append df = df.append(pd.DataFrame( list,                columns=[ 'Name', 'Age', 'City', 'Country']),                ignore_index = True)   # display df display(df)

输出:

如何在Python中把一个列表作为一行追加到Pandas DataFrame中?



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有